# -*- coding: utf-8 -*-
from django.shortcuts import render,render_to_response, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from register import  settings
from models import Consumption , Price,Charge
from register.models import User
from compiler.pycodegen import EXCEPT
import time
from register.keystone_util import Keystone
import decimal
from decimal import Decimal
from django.core import serializers

# Create your views here.
def consumption_list(req):
    
    page = req.GET.get('page')
    consumption_list = Consumption.objects.filter()
    paginator = Paginator(consumption_list, settings.PAGE_ITEMS_SHOW) # Show 25 contacts per page
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
    # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render_to_response('billing/consumption_list.html', {'contacts':contacts}, context_instance=RequestContext(req))

def consumption_add(req):
    
    user_id = req.session['user_id'] 
    keyclient = Keystone()
    v_client = keyclient.admin_login()
    project = keyclient.get_tenant(v_client,user_id)
    project_id = project.id
    project_name = project.name
    currentTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    
    concou = ConsumptionCount()
    all_count = concou.getConsumptionAll(project_id,currentTime)
    cpu_count = concou.getCpuUseCount(project_id,currentTime)
    disk_count = concou.getDiskUseCount(project_id,currentTime)
    memory_count = concou.getMemoryUseCount(project_id,currentTime)
    
    memoryPrice = Price.objects.filter(price_name='内存').filter(status=0)[0].unit_price
    diskPrice = Price.objects.filter(price_name='磁盘').filter(status=0)[0].unit_price
    cpuPrice = Price.objects.filter(price_name='vcpu').filter(status=0)[0].unit_price
    try:
        last_remaining_money =   Consumption.objects.filter(project_id=project_id).order_by('-record_time')[0].remaining_money
    except:
        last_remaining_money = Decimal(0)
    if req.method == 'POST':
        consume_money = (Decimal(cpu_count) * Decimal(cpuPrice) + Decimal(disk_count) * Decimal(diskPrice) + Decimal(memory_count) * Decimal(memoryPrice))
        remaining_money = Decimal(last_remaining_money) + consume_money
        cpu_consume_money = Decimal(cpu_count) * Decimal(cpuPrice) 
        disk_consume_money = Decimal(disk_count) * Decimal(diskPrice)  
        memory_consume_money = Decimal(memory_count) * Decimal(memoryPrice)
        con = Consumption(project_id=project_id,project_name=project_name,cpu_price = cpuPrice,disk_price = diskPrice,memory_price = memoryPrice,
                          consume_money = consume_money,cpu_use_count = cpu_count,memory_use_count=memory_count,disk_use_count=disk_count,
                          remaining_money=remaining_money,cpu_consume_money=cpu_consume_money,disk_consume_money=disk_consume_money,memory_consume_money=memory_consume_money) 
        con.save() 
        return redirect('consumption_list')
    else:
        content = {'project_id':project_id,"project_name":project_name,"count":all_count,"cpuPrice":cpuPrice,"diskPrice":diskPrice,"memoryPrice":memoryPrice}
        return render_to_response('billing/consumption_add.html', content, context_instance=RequestContext(req))
    
def consumption_query_by_project_id(req):
    
    projectId = req.GET.get("project_id")
    
    page = req.GET.get('page')
    consumption_list = Consumption.objects.filter(project_id = projectId)
    paginator = Paginator(consumption_list, settings.PAGE_ITEMS_SHOW) # Show 25 contacts per page
    
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
    # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render_to_response('billing/consumption_list.html', {'contacts':contacts}, context_instance=RequestContext(req))

def price_list(req):
    
    price_list = Price.objects.all().filter(status = 0)
    
    return render_to_response('billing/price_list.html', {'contacts':price_list}, context_instance=RequestContext(req))

def price_add(req):
    
    if req.method == 'POST':
        price_name = req.POST.get('price_name')
        unit = req.POST.get('unit')
        unit_price = req.POST.get('unit_price')
        price_list = Price.objects.all().filter(price_name = price_name)
        if price_list.count() > 0 :
            price_list.update(status = 1)
        p = Price(price_name = price_name,unit = unit,unit_price = unit_price)
        p.save()
        return redirect('price_list')
    else:
        return render_to_response('billing/price_add.html',context_instance=RequestContext(req))

def price_delete(req,price_id):
    result = Price.objects.filter(id=price_id).delete()
    return redirect('price_list')

def price_update(req,price_id):
    price = Price.objects.get(id=price_id)
    return render_to_response('billing/price_update.html',{'price':price},context_instance=RequestContext(req))
    
def price_history_list(req):
    price_list = Price.objects.all().filter(status = 1)
    return render_to_response('billing/price_history.html',{'contacts':price_list},context_instance=RequestContext(req))

def ajax_get_consumption_data(req):
    json_data = serializers.serialize("json",Consumption.objects.all())
    return HttpResponse(json_data,content_type="application/json")

def personal_account_info(req):
    if req.session.has_key('user_id') :
        user_id = req.session['user_id']
        user = User.objects.all().filter(keystone_user_id = user_id)[0];
        keyclient = Keystone()
        v_client = keyclient.admin_login()
        project = keyclient.get_tenant(v_client,user_id)
        user_consumption_list = Consumption.objects.all().filter(project_id = project.id).order_by("-record_time")
        user_charge_list = Charge.objects.all().filter(project_id = project.id).order_by("-txnTime")
          
        consume_money = Decimal(0)
        for temp_consume in user_consumption_list:
            if temp_consume.consume_money >= 0:
                consume_money += temp_consume.consume_money
        tempchargelist=user_charge_list.filter(status = 1)
        charge_money = Decimal(0)
        for temp_charge in tempchargelist:
            if temp_charge.status == 1:
                charge_money += temp_charge.txnAmt
        try:
            latest_charge = tempchargelist[0].txnAmt
        except:
            latest_charge = Decimal(0)
        
        tempcon = user_consumption_list.filter(consume_money__gte=Decimal(0))
        if tempcon.count() > 0:
            latest_consume = tempcon[0].consume_money
        else:
            latest_consume = Decimal(0)
        if user_consumption_list.count() >0 :
            user_money = user_consumption_list[0].remaining_money
        else:
            user_money = Decimal(0)
           
        return render_to_response('billing/personal_account_info.html',{'user':user,'user_money':user_money,'charge_money':charge_money,'consume_money':consume_money,'user_consumption_list':user_consumption_list,'user_charge_list':user_charge_list,"latest_consume":latest_consume,"latest_charge":latest_charge},context_instance=RequestContext(req))
    else :
        return HttpResponseRedirect('/error/')
    